package com.jl.util;

import com.jl.code.entity.WeiXinUser;
import com.jl.config.WeiXinSignUtil;
import com.jl.pojo.AccessToken;
import com.jl.pojo.Template;
import com.jl.pojo.WeixinOauth2Token;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class AdvancedUtil {

    public static Logger logger= LoggerFactory.getLogger(AdvancedUtil.class);

    /**
     * 获取网页授权凭证
     * @param  appId  公众号的唯一标识
     * @param appSecret  公众号的密钥
     * @param code
     * @return WeixinOauth2Token
     */
    public static WeixinOauth2Token getOauth2Token(String appId, String appSecret, String code){

        String requestUrl="https://api.com.jl.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

        requestUrl=requestUrl.replace("APPID",appId);
        requestUrl=requestUrl.replace("SECRET",appSecret);
        requestUrl=requestUrl.replace("CODE",code);

        WeixinOauth2Token wat=null;

        //获取网页授权的凭证
        JSONObject jsonObject=JsapiTicketUnit.httpRequest(requestUrl,"GET",null);

        if(null!=jsonObject){

            try {

                wat=new WeixinOauth2Token();
                wat.setAccessToken(jsonObject.getString("access_token"));
                wat.setExpiresIn(jsonObject.getInt("expires_in"));
                wat.setOpenId(jsonObject.getString("openid"));
                wat.setRefreshToken(jsonObject.getString("refresh_token"));
                wat.setScope(jsonObject.getString("scope"));
            }catch (Exception e){

                wat=null;
                int errorCode=jsonObject.getInt("errcode");
                String errorMsg=jsonObject.getString("errmsg");
                logger.error("获取网页授权失败",errorCode,errorMsg);
            }

        }


        return wat;
    }


    /**
     * 通过网页授权获取用户的信息
     * @param accessToken
     * @param openId
     *
     */
    public static WeiXinUser getWeiXinUser(String accessToken, String openId){

        //拼接请求的地址
        String requestUrl="https://api.com.jl.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";

        requestUrl=requestUrl.replace("ACCESS_TOKEN",accessToken).replace("OPENID",openId);

        //获取网页授权的凭证
        JSONObject jsonObject=JsapiTicketUnit.httpRequest(requestUrl,"GET",null);

        WeiXinUser weiXinUser=null;

        if(null!=jsonObject){


            try {

                weiXinUser=new WeiXinUser();
                //用户的标识
                weiXinUser.setOpenId(jsonObject.getString("openid"));
                //昵称
                weiXinUser.setNickname(jsonObject.getString("nickname"));
                //性别（1是男 2是女 0是未知）
                weiXinUser.setSex(jsonObject.getInt("sex"));
                //用户所在的国家
                weiXinUser.setCountry(jsonObject.getString("country"));
                //用户所在的省份
                weiXinUser.setProvince(jsonObject.getString("province"));
                //用户所在的城市
                weiXinUser.setCity(jsonObject.getString("city"));
                //用户的头像
                weiXinUser.setHeadImgUrl(jsonObject.getString("headimgurl"));
                //用户的特权信息
                /* weiXinUser.setPrivilegeList(JSONArray.toList(jsonObject.getJSONArray("privilege"), List.class));*/

            }catch (Exception e){

                weiXinUser=null;
                int errorCode=jsonObject.getInt("errcode");
                String errorMsg=jsonObject.getString("errmsg");
                logger.error("获取用户信息失败",errorCode,errorMsg);

            }


        }

        return weiXinUser;

    }

    /**
     * 发送模板消息
     */
    public static int sendTemplateMsg(String accessToken, Template template){

        int result=0;

        String requestUrl="https://api.com.jl.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN";

        requestUrl=requestUrl.replace("ACCESS_TOKEN",accessToken);

        JSONObject jsonObject=JsapiTicketUnit.httpRequest(requestUrl,"POST",template.toJSON());

        if(null!=jsonObject){

            int errorCode= jsonObject.getInt("errcode");
            String errorMsg=jsonObject.getString("errmsg");

            if(0 == errorCode){

                result=1;

                System.out.println("模板消息发送成功 errcode{}"+errorCode+"-----"+errorMsg);
            }

            System.out.println("模板消息发送失败 errcode{}"+errorCode+"-----"+errorMsg);

        }

        return result;

    }


    /**
     * 获取jsapi的凭证票据
     */
    public static String getJSApi(){

        AccessToken accessToken = JsapiTicketUnit.getAccessToken(WeiXinSignUtil.appid, WeiXinSignUtil.appSecret);

        System.out.println(accessToken.getToken());

        String urlStr="https://api.com.jl.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken.getToken()+"&type=jsapi";

        JSONObject jsonObject=JsapiTicketUnit.httpRequest(urlStr,"GET","10000");


        return (String)jsonObject.get("ticket");

    }


    /**
     * 获取三大凭证
     */
    public static Map<String,String> sign(String jsapi,String url){

        Map<String,String> ret=new HashMap<String,String>();


        String noce_str=create_noce_str();
        String timestamp=create_timestamp();
        String signature="";

        //必须要全部小写，并且全部是有序的
        String  string1="jsapi_ticket="+jsapi+
                "&nonceStr="+noce_str+
                "&timestamp="+timestamp+
                "&url="+url;

        System.out.println("打印创建的参数串"+string1);

        try{

            MessageDigest crypt=MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature=byteToHex(crypt.digest());

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        System.out.println("signature="+signature);

        ret.put("url",url);
        ret.put("jsapi_ticket",jsapi);
        ret.put("nonceStr",noce_str);
        ret.put("timestamp",timestamp);
        ret.put("signature",signature);


        return ret;

    }

    private static String byteToHex(final byte[] digest) {

        Formatter formatter=new Formatter();

        for(byte b:digest){

            formatter.format("%02x",b);
        }

        String result=formatter.toString();

        formatter.close();

        return result;


    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis()/1000);
    }

    private static String create_noce_str() {

        return UUID.randomUUID().toString();

    }



      public static String evaluateCoordinates(BigDecimal xa, BigDecimal ya, BigDecimal xb, BigDecimal yb, BigDecimal xc, BigDecimal yc, BigDecimal ra, BigDecimal rb, BigDecimal rc){

        BigDecimal a2 = ra.multiply(ra);
        BigDecimal b2 = rb.multiply(rb);
        BigDecimal c2 = rc.multiply(rc);
        BigDecimal xa2 = xa.multiply(xa);
        BigDecimal xb2 = xb.multiply(xb);
        BigDecimal xc2 = xc.multiply(xc);
        BigDecimal ya2 = ya.multiply(ya);
        BigDecimal yb2 = yb.multiply(yb);
        BigDecimal yc2 = yc.multiply(yc);

        BigDecimal rbc = b2.subtract(c2);
        BigDecimal xbc = xb2.subtract(xc2);
        BigDecimal ybc = yb2.subtract(yc2);

        BigDecimal va = rbc.subtract(xbc).subtract(ybc).divide(new BigDecimal("2.0"));

        BigDecimal rba = b2.subtract(a2);
        BigDecimal xba = xb2.subtract(xa2);
        BigDecimal yba = yb2.subtract(ya2);

        BigDecimal vb = rba.subtract(xba).subtract(yba).divide(new BigDecimal("2.0"));

        BigDecimal xcb = xc.subtract(xb);
        BigDecimal xab = xa.subtract(xb);
        BigDecimal yab = ya.subtract(yb);
        BigDecimal ycb = yc.subtract(yb);

        BigDecimal va1 = va.multiply(xab);
        BigDecimal vb1 = vb.multiply(xcb);
        BigDecimal aa = yab.multiply(xcb);
        BigDecimal ab = ycb.multiply(xab);

        BigDecimal y1 = vb1.subtract(va1);
        BigDecimal y2 = aa.subtract(ab);
        BigDecimal y = y1.divide(y2,10, RoundingMode.DOWN);

        BigDecimal x;
        if (xcb.signum() != 0) {
            x = va.subtract((y.multiply(ycb))).divide(xcb,10,RoundingMode.DOWN);
        } else {
            x = vb.subtract(y.multiply(yab)).divide(xab,10,RoundingMode.DOWN);
        }

        System.out.println("坐标为（"+x+","+y+")");

        return "成功";
    }


}
